package com.example.aws_s3_practice;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

import android.app.Activity;
import android.app.Fragment;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;

import com.amazonaws.AmazonClientException;
import com.amazonaws.AmazonServiceException;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.amazonaws.services.s3.model.PutObjectRequest;
import com.amazonaws.services.s3.model.S3Object;


public class S3Fragment extends Fragment {
	
	private AmazonS3Client s3Client;
	private OnDownloadFinishedListener mCallback;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		s3Client = new AmazonS3Client(
				new BasicAWSCredentials(getString(R.string.access_key_id), 
						getString(R.string.secret_key)));
		/*
		try {
			if(!s3Client.doesBucketExist(getString(R.string.bucket_name))) {
				s3Client.createBucket(getString(R.string.bucket_name));
				Log.d("TEST", "This should not print if the bucket has been created");
			}
		} catch (AmazonServiceException e) {
			Log.e("TODO", "Error occured in S3 while processing request");
		} catch (AmazonClientException e) {
			Log.e("TODO","Error occured while making request of handling response");
		}
		*/
	}
	
	public interface OnDownloadFinishedListener {
		public void onDownloadFinished(String result);
	}
	
	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);
		
		// This makes sure that the container activity has implemented
		// the callback interface. If not, it throws an exception
		try {
			mCallback = (OnDownloadFinishedListener) activity;
		} catch (ClassCastException e) {
			throw new ClassCastException(activity.toString() 
					+ " must implement OnDownloadFinishedListener"); 
		}
	}
	
	public void uploadToBucket(String mString, String mStringKey, String mBucket) {
		new UploadToBucketTask().execute(mString, mStringKey, mBucket);
	}
	
	private class UploadToBucketTask extends AsyncTask<String, Void, Void> {

		@Override
		protected Void doInBackground(String... params) {
			
			if(params == null || params.length != 3) {
				return null;
			}
			
			String mString = params[0];
			String mStringKey = params[1];
			String mBucket = params[2];
			
			try {
				if(!s3Client.doesBucketExist(mBucket)) {
					Log.d("TEST", "This should not print if the bucket has been created");
				}
			} catch (AmazonServiceException e) {
				Log.e("TODO", "Error occured in S3 while processing request");
			} catch (AmazonClientException e) {
				Log.e("TODO","Error occured while making request of handling response");
			}
			
			ByteArrayInputStream input = new ByteArrayInputStream(mString.getBytes());
			ObjectMetadata metadata = new ObjectMetadata();
			metadata.setContentLength(mString.getBytes().length );
			PutObjectRequest por = new PutObjectRequest(mBucket,
						mStringKey, input, metadata);
			try {
				s3Client.putObject(por);
			} catch (AmazonServiceException e) {
				Log.e("TODO", "Error occured in S3 while processing request");
			} catch (AmazonClientException e) {
				Log.e("TODO","Error occured while making request of handling response");
			}
			return null;
		}	
	}
	
	public void downloadFromBucket(String mStringKey, String mBucket) {
		new DownloadFromBucketTask().execute(mStringKey, mBucket);
	}
	
	private class DownloadFromBucketTask extends AsyncTask<String, Void, String> {

		@Override
		protected String doInBackground(String... params) {
			StringBuilder builder = new StringBuilder();
			String mStringKey = params[0];
			String mBucket = params[1];
			
			try {
				if(!s3Client.doesBucketExist(mBucket)) {
					Log.d("TEST", "This should not print if the bucket has been created");
				}
			} catch (AmazonServiceException e) {
				Log.e("TODO", "Error occured in S3 while processing request");
			} catch (AmazonClientException e) {
				Log.e("TODO","Error occured while making request of handling response");
			}
			
			S3Object s3Object = null;
			try {
				s3Object = s3Client.getObject(mBucket, mStringKey);
				Log.d("TEST", s3Object.toString());
			} catch (AmazonServiceException e) {
				Log.e("TODO", "Error occured in S3 while processing request");
			} catch (AmazonClientException e) {
				Log.e("TODO","Error occured while making request of handling response");
			}
			
			InputStream input = s3Object.getObjectContent();
			
			int c;
			try {
				while( (c = input.read()) != -1) {
					builder.append((char) c);
				}
			} catch (IOException e) {
				Log.d("Error", "IOException when reading from input");
			}
			
			return builder.toString();
		}	
		
		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			mCallback.onDownloadFinished(result);
		}
	}
}